package servlets;

import java.io.IOException;
import java.util.ListIterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import dataTypes.*;



@SuppressWarnings("serial")
public class c2dmRegistrationServlet extends HttpServlet {
	public c2dmRegistrationServlet() {
		super();
	}


	private static final Logger log =
		Logger.getLogger(c2dmRegistrationServlet.class.getName());
	private static final String OK_STATUS = "OK";
	private static final String LOGIN_REQUIRED_STATUS = "LOGIN_REQUIRED";
	private static final String ERROR_STATUS = "ERROR";

	private static int MAX_DEVICES = 5;

	/**
	 * Get the user using the UserService.
	 *
	 * If not logged in, return an error message.
	 *
	 * @return user, or null if not logged in.
	 * @throws IOException
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.setContentType("text/plain");

		// Basic XSRF protection
		if (req.getHeader("X-Same-Domain") == null) {
			log.warning("Blocked XSRF");
			resp.setStatus(400);
			resp.getWriter().println(ERROR_STATUS + " (Missing X-Same-Domain header)");
			return;
		}

		String deviceRegistrationId = req.getParameter("devregid");
		if (deviceRegistrationId == null || "".equals(deviceRegistrationId.trim())) {
			resp.setStatus(400);
			resp.getWriter().println(ERROR_STATUS + "(Must specify devregid)");
			log.severe("Missing registration id ");
			return;
		}

		String deviceId = req.getParameter("deviceId");

		String deviceMailaddress = req.getParameter("deviceMail");

		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			
			appManager.getInstance().addUsertoDB(deviceMailaddress,deviceRegistrationId,deviceId);
			ListIterator<userDevice> iter=appManager.getInstance().users.listIterator();
			/**while (iter.hasNext()){
				userDevice u=iter.next();
				if (u.getGoogleName().equals(userDevice.getGoogleName())&&userDevice.getDeviceRegistrationID()!=null){
					appManager.getInstance().users.remove(u);
					appManager.getInstance().users.add(userDevice);
					break;
				}
			}**/
			
			
			
		} catch (Exception e) {
			resp.setStatus(500);
			resp.getWriter().println(ERROR_STATUS + " (Error registering device)");
			log.log(Level.WARNING, "Error registering device.", e);
		} finally {
			pm.close();
		}

	}



}
